package com.byt.framlib.basemvp.network;


import androidx.annotation.Nullable;

import com.byt.framlib.basemvp.basebean.BaseResponseBean;
import com.byt.framlib.basemvp.exception.ExceptionFunc;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 类名称：  HttpManager
 * 创建时间：2017/10/25
 * 类描述：  http请求管理器
 */
public class HttpManager {

    /**
     * 发送post请求
     *
     * @param observable 接口方法返回参数
     * @param subscriber 自定义subscriber
     *                   onErrorResumeNext(new ExceptionFunc())
     */
    public <T> void http(Observable<BaseResponseBean<T>> observable, Observer<BaseResponseBean<T>> subscriber) {
        observable.compose(applySchedulers())
                .unsubscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    /**
     * 发送post请求
     *
     * @param observable 接口方法返回参数
     * @param subscriber 自定义subscriber
     *                   onErrorResumeNext(new ExceptionFunc())
     */
    public <T> void http(Observable<BaseResponseBean<T>> observable, @Nullable ObservableTransformer transformer, Observer<BaseResponseBean<T>> subscriber) {
        observable.compose(transformer)
                .onErrorResumeNext(new ExceptionFunc())
                .compose(applySchedulers())
                .unsubscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public <R> ObservableTransformer<R, R> applySchedulers() {
        return new ObservableTransformer<R, R>() {
            @Override
            public ObservableSource<R> apply(Observable<R> upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }

        };
    }
}